package com.lxm.shownews.channel.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.lxm.shownews.R;
import com.lxm.shownews.bean.News;
import com.lxm.shownews.channel.ChannelJsonUtils;
import com.lxm.shownews.channel.OnRecyclerViewListener;
import com.lxm.shownews.channel.adapter.NewsRecyclerAdapter;
import com.lxm.shownews.commons.Urls;
import com.lxm.shownews.detail.DetailActivity;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lxm on 2016/2/23.
 */
public class BaseFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, OnRecyclerViewListener {

    OkHttpClient okHttp;
    private int page = 1;
    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeLayout;
    private NewsRecyclerAdapter recyclerAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private List<News> newsList = new ArrayList<>();
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                List<News> mNewsList = (List<News>) msg.obj;
                Log.i("handler---", mNewsList.toString());
                recyclerAdapter.addMore(mNewsList);
                swipeLayout.setRefreshing(false);
            }

        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_channel, container, false);
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeLayout);
        swipeLayout.setOnRefreshListener(this);
        recyclerView = (RecyclerView) view.findViewById(R.id.recycler);
        mLayoutManager = new LinearLayoutManager(this.getActivity());
        recyclerView.setLayoutManager(mLayoutManager);
        //如果可以确定每个item的高度是固定的，设置这个选项可以提高性能
//        recyclerView.setHasFixedSize(true);
        recyclerAdapter = new NewsRecyclerAdapter(newsList);
        recyclerAdapter.setmOnRecyclerClickListener(this);
        recyclerView.setAdapter(recyclerAdapter);
        okHttp = new OkHttpClient();
        swipeLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeLayout.setRefreshing(true);
            }
        });
        onRefresh();
    }

    private void loadData(int loadPage) {
        Request request = new Request.Builder()
                .url(Urls.URL_CHANNEL_SEARCH_NEWS + "?channelId=5572a109b3cdc86cf39001db&page=" + loadPage)
                .addHeader("apikey", Urls.BAIDU_API_KEY).build();
        okHttp.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Log.i("----onFailure----", request.toString());
            }

            @Override
            public void onResponse(Response response) throws IOException {
                //Not UI thread
                if (response.isSuccessful()) {
                    String res = response.body().string();
                    System.out.println(response.code());
                    List<News> newsList = ChannelJsonUtils.readNews(res);
                    Message msg = new Message();
                    msg.obj = newsList;
                    msg.what = 1;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    @Override
    public void onRefresh() {
        loadData(1);
        //
//        swipeLayout.setRefreshing(false);
    }

    @Override
    public void onItemClick(View view, int position, Object tag) {
        Toast.makeText(getContext(), "ItemClick--" + ((News) tag).getTitle(), Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(this.getActivity(), DetailActivity.class);
//        intent.putExtras()
        Bundle bundle = new Bundle();
        bundle.putParcelable("news", (News) tag);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    public boolean onItemLongClick(int position, Object tag) {
        return false;
    }

    @Override
    public void onEventClick(int position, Object tag) {
        Toast.makeText(getContext(), "onEventClick--", Toast.LENGTH_SHORT).show();
    }
}
